package com.exam.Controller;

import com.exam.Entity.ApiResult;
import com.exam.Entity.Student;
import com.exam.Service.StudentService;
import com.exam.util.ApiResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/students/{page}/{size}")
    public ApiResult findAll(@PathVariable Integer page, @PathVariable Integer size) {
//        Page<Student> studentPage = new Page<>(page,size);
//        IPage<Student> res = studentService.findAll(studentPage);
//        return  ApiResultHandler.buildApiResult(200,"分页查询所有学生",res);
        ApiResult apiResult;
        List<Student> res = studentService.findAll(page,size);
        List<Student> t = studentService.findTotal(page,size);
        // 构造返回数据
        Map<String, Object> data = new java.util.HashMap<>();
        data.put("records", res);               // 返回的试卷列表
        data.put("current", page);              // 当前页码
        data.put("size", size);                 // 每页大小
        data.put("total", t.size());          // 总记录数（列表长度）

        // 构建 ApiResult
        apiResult = ApiResultHandler.buildApiResult(200, "请求成功！", data);

        return apiResult;
    }

    @GetMapping("/student/{sno}")
    public ApiResult findById(@PathVariable("sno") Integer sno) {
        Student res = studentService.findById(sno);
        if (res != null) {
        return ApiResultHandler.buildApiResult(200,"请求成功",res);
        } else {
            return ApiResultHandler.buildApiResult(404,"查询的用户不存在",null);
        }
    }

    @DeleteMapping("/student/{studentId}")
    public ApiResult deleteById(@PathVariable("studentId") Integer studentId) {
        System.out.println(studentId);
        return ApiResultHandler.buildApiResult(200,"删除成功",studentService.deleteById(studentId));
    }

    @PutMapping("/studentPWD")
    public ApiResult updatePwd(@RequestBody Student student) {
        studentService.updatePwd(student);
        return ApiResultHandler.buildApiResult(200,"密码更新成功",null);
    }
    @PutMapping("/student")
    public ApiResult update(@RequestBody Student student) {
        int res = studentService.update(student);
        if (res != 0) {
            return ApiResultHandler.buildApiResult(200,"更新成功",res);
        }
        return ApiResultHandler.buildApiResult(400,"更新失败",res);
    }

    @PostMapping("/student")
    public ApiResult add(@RequestBody Student student) {
        int res = studentService.add(student);
        if (res == 1) {
            return ApiResultHandler.buildApiResult(200,"添加成功",null);
        }else {
            return ApiResultHandler.buildApiResult(400,"添加失败",null);
        }
    }
}
